import 'package:flutter/material.dart';

class GridDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _GridDemoState();
  }
}

class _GridDemoState extends State {
  List<IconData> _icons = []; //保存Icon数据

  @override
  void initState() {
    // 初始化数据
    _retrieveIcons();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Grid View 例子'),
      ),

      body: Column(
        children: <Widget>[
          // 说明
          ListTile(title:Text("图片列表")),

          // 内容区域
          Expanded(
            child: GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
              ),
              itemBuilder: (context, index) {
                //如果显示到最后一个并且Icon总数小于200时继续获取数据
                if (index == _icons.length - 1 && _icons.length < 200) {
                  _retrieveIcons();
                }
                return Icon(_icons[index]);
              },
              itemCount: _icons.length,
            ),
          ),

          // 占位，
          SizedBox(
            height: 50,
          ),
        ],
      ),
    );
  }

  //模拟异步获取数据
  void _retrieveIcons() {
    Future.delayed(Duration(milliseconds: 200)).then((e) {
      setState(() {
        _icons.addAll([
          Icons.ac_unit,
          Icons.airport_shuttle,
          Icons.all_inclusive,
          Icons.beach_access,
          Icons.cake,
          Icons.free_breakfast,
        ]);
      });
    });
  }
}